package com.acme.server;


import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

import com.acme.bankapp.domain.bank.Bank;
import com.acme.bankapp.service.bank.BankReport;

public class BankServer {
	
	public static final String CMD_ADD = "add";
	public static final String CMD_BALANCE = "getBalance";
	public static final String CMD_BYE = "bye";
	
	public static final String CLIENT = "client>";
	public static final String ERROR_MSG = "Data received in unknown format";
	
	ServerSocket providerSocket;
	Socket connection = null;
	ObjectOutputStream out;
	ObjectInputStream in;
	String message;
	
	public BankServer() {
	}

	
	public void startServer(Bank bank) {
		try {
			startServer();
			waitConnection();
			
			BankReport bankReport = new BankReport();
			do {
				try {
					 message = (String) in.readObject();
                     System.out.println(BankServer.CLIENT + message);
                     if (message.equals(BankServer.CMD_ADD)) {
                    	 message = (String) in.readObject();
                         System.out.println(BankServer.CLIENT  + message);
                         bankReport.addClient(bank, message);
                     }

                     if (message.equals(BankServer.CMD_BALANCE)) {
                         sendMessage(bankReport.getBalance(bank));
                     }
                     if (message.equals(BankServer.CMD_BYE))
                         sendMessage(BankServer.CMD_BYE);                                      
				} catch (ClassNotFoundException classnot) {
					System.err.println(BankServer.ERROR_MSG);
				}
			} while (!message.equals(BankServer.CMD_BYE));
		} catch (IOException ioException) {
			ioException.printStackTrace();
		} finally {
			try {
				in.close();
				out.close();
				providerSocket.close();
			} catch (IOException ioException) {
				ioException.printStackTrace();
			}
		}
	}
	
	void startServer() throws IOException{
		providerSocket = new ServerSocket(2004, 10);
		System.out.println("Waiting for connection");
	}
	
	void waitConnection() throws IOException{
		connection = providerSocket.accept();
		System.out.println("Connection received from " + connection.getInetAddress().getHostName());
		out = new ObjectOutputStream(connection.getOutputStream());
		out.flush();
		in = new ObjectInputStream(connection.getInputStream());
		sendMessage("Connection successful");
	}

	void sendMessage(final String msg) {
		try {
			out.writeObject(msg);
			out.flush();
			System.out.println("server>" + msg);
		} catch (IOException ioException) {
			ioException.printStackTrace();
		}
	}

}


